package com.youfang.sixthmedia.net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;

import ch.boye.httpclientandroidlib.Header;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.NameValuePair;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.protocol.HTTP;

/**
 * 从服务器下载apk
 * 
 * @author teddy
 * 
 */
public class VersionDownloader implements Runnable {

	public static interface FetcherListener {

		/**
		 * @param total
		 *            包的大小，字节
		 * @param received
		 *            接收到多少，字节
		 */
		void onReceive(int total, int received);

		void onFinish(File apkFile);

		void onError();

		void onInterrupt();

	}

	// 下载时开辟的缓存大小
	private static final int DEF_BUFFER_SIZE = 1024 * 2;
	private int bufferSize = DEF_BUFFER_SIZE;

	// 是否需要中断下载
	private boolean isNeedInterrupt;

	// 向服务端传递的参数
	private Pair[] params;

	// apk所在的远端http url,该值必须指定
	private String url;

	// 本地存储apk的地址
	private String localDir;

	// apk下载后保存到本地的文件名
	private String localApkFileName;

	// 下载过程中的过程监听器
	private FetcherListener listener;

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

	public VersionDownloader setParams(Pair[] params) {
		this.params = params;
		return this;
	}

	public String getUrl() {
		return url;
	}

	public VersionDownloader setUrl(String url) {
		this.url = url;
		return this;
	}

	public String getLocalDir() {
		return localDir;
	}

	public VersionDownloader setLocalDir(String localDir) {
		this.localDir = localDir;
		return this;
	}

	public String getLocalApkFileName() {
		return localApkFileName;
	}

	public VersionDownloader setLocalApkFileName(String localApkFileName) {
		this.localApkFileName = localApkFileName;
		return this;
	}

	public FetcherListener getListener() {
		return listener;
	}

	public VersionDownloader setListener(FetcherListener listener) {
		this.listener = listener;
		return this;
	}

	// 通过该接口启动下载
	Thread downloadThread;

	public VersionDownloader start() {
		downloadThread = new Thread(this);
		downloadThread.start();
		return this;
	}

	// 中断下载线程
	public synchronized boolean interrupt() {
		this.setNeedInterrupt(true);
		if (downloadThread != null && downloadThread.isAlive()) {
			downloadThread.interrupt();
		}

		if (this.listener != null) {
			this.listener.onInterrupt();
		}
		return true;

	}

	public synchronized boolean isInterrupted() {
		return isNeedInterrupt;
	}

	public synchronized void setNeedInterrupt(boolean isNeedInterrupt) {
		this.isNeedInterrupt = isNeedInterrupt;
	}

	// 下载时候保存到的文件，下载开始前确保该文件对象存在
	private File localAPKFile;

	public File getLocalAPKFile() {
		return localAPKFile;
	}

	private String genApkFileName() {
		return "apk_" + System.currentTimeMillis() + ".apk";
	}

	// 如果本地文件的保存目录未设定则使用系统的临时目录存储apk包
	private boolean ensureLocalApkFile() throws IOException {

		// 有指定apk包的存储目录，则在SD卡的对应目录下面创建文件
		if (localDir != null) {
			File dir = new File(localDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			// 没有指定文件名，则声称一随机文件名
			if (this.localApkFileName == null) {
				this.localApkFileName = genApkFileName();
			}

			localAPKFile = new File(this.localDir + File.separator
					+ this.localApkFileName);
			localAPKFile.delete();
			return true;

		}

		// 使用系统的临时目录存储apk包
		this.localAPKFile = File.createTempFile("kingdee", genApkFileName());
		return true;

	}

	@Override
	public void run() {

		try {
			this.ensureLocalApkFile();
		} catch (IOException e) {
			e.printStackTrace();
			if (this.listener != null) {
				this.listener.onError();
			}
			return;
		}

		// 开始下载
		this.download();

	}

	private boolean download() {

		HttpClient httpClient = HttpRemoter.getYoufangRemoter().getHttpClient();

		OutputStream fos = null;
		InputStream is = null;
		try {

			// 设置参数并发起请求
			URI uri = new URI(this.url);
			HttpGet httpPost = new HttpGet(uri);

			HttpResponse response = httpClient.execute(httpPost);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity httpEntity = response.getEntity();
				is = httpEntity.getContent();
			}

			// 获得文件大小
			Header[] headsFSize = response.getHeaders("Content-Length");
			int contentLength = 0;
			if (headsFSize != null) {
				contentLength = Integer.valueOf(headsFSize[0].getValue());
			}

			// 把下载后的数据写入本地文件
			fos = new FileOutputStream(localAPKFile);
			int mark = 0;
			byte[] temp = new byte[bufferSize];
			int hasRead = 0;
			while ((mark = is.read(temp)) != -1) {
				fos.write(temp, 0, mark);
				hasRead += mark;
				if (this.listener != null) {
					this.listener.onReceive(contentLength, hasRead);
				}
			}

			fos.flush();
			if (this.listener != null) {
				this.listener.onFinish(localAPKFile);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			if (this.listener != null) {
				this.listener.onError();
			}
			return false;
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}